package com.zanglikun.rocketmq.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

/**
 * @Author: zanglikun
 * @Date: 2022/3/31 19:37
 * @Description: 顺序生产者
 */
public class SelecterProducer {
    public static void main(String[] args) throws Exception {
        // todo 1 创建消息生产者对象,同时指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        // todo 2 指定NameServer地址
        producer.setNamesrvAddr("192.168.253.128:9876;192.168.253.129:9876");
        // todo 3 启动生产者
        producer.start();
        List<OrderStep> orderSteps = OrderStep.buildOrderSteps();
        for (int i = 0; i < 10; i++) {
            String body = orderSteps.get(i) + "";
            // todo 4 创建消息对象,同时指定topic、tags、body
            Message message = new Message("OrderTopic", "Order", body.getBytes());
            // todo 5 发送消息 参数依次是：消息、消息队列选择器、选择器业务标识(注意，业务标识一般为订单号，MQ就会以业务标识发送到同一个队列中)
            SendResult sendResult = producer.send(message, new MessageQueueSelector() {
                /**
                 * @param list 消息集合
                 * @param message 消息对象
                 * @param o 业务标识参数
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    long orderId = (long) o;
                    long index = orderId%list.size();
                    return list.get((int)index);
                }
            }, orderSteps.get(i).getOrderId());
            // todo 6 处理发送结果
            SendStatus sendStatus = sendResult.getSendStatus();
            String msgId = sendResult.getMsgId();
            int queueId = sendResult.getMessageQueue().getQueueId();
            System.out.println("消息发送状态" + sendStatus + ",消息Id:" + msgId + ",消息队列Id" + queueId);
            Thread.sleep(500);
        }
        // todo 7 关闭生产者
        producer.shutdown();
    }
}
